package com.webrtc.demo.util

import android.content.Context
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson
import com.webrtc.demo.model.Contacts
import java.io.IOException
import java.util.*

object ContactsUtils {

    private const val TAG = "ContactsUtils"

    private const val SP_MY_UID = "my_uid"
    private const val SP_CONTACTS_LIST = "contacts_list"

    fun getMyUid(context: Context): String {
        var uid = Utils.getSharedPreferences(context).getString(SP_MY_UID, null)
        if (uid == null) {
//            uid = UUID.randomUUID().toString()
            uid = String.format("%06d", (0..999999).random())
            val result =
                Utils.getSharedPreferences(context).edit().putString(SP_MY_UID, uid).commit()
            if (!result) throw IOException("write my uid to sp error!")
        }
        logD(TAG, "my uid=$uid")
        return uid
    }

    fun getContactsList(context: Context): ArrayList<Contacts>? {
        val str = Utils.getSharedPreferences(context).getString(SP_CONTACTS_LIST, null)
        return str?.let {
            Gson().fromJson(str)
        }
    }

    fun saveContactsList(context: Context, contactsList: ArrayList<Contacts>) {
        Utils.getSharedPreferences(context).put(SP_CONTACTS_LIST, Gson().toJson(contactsList))
    }

    fun addContacts(context: Context, name: String, nickname: String? = null): Boolean {
        val contactsList = getContactsList(context) ?: arrayListOf()
        contactsList.forEach {
            if (it.uid == name) {
                return false
            }
        }
        contactsList.add(0, Contacts(name, null, nickname))
        saveContactsList(context, contactsList)
        return true
    }

    fun removeContacts(context: Context, name: String) {
        val contactsList = getContactsList(context) ?: return
        val iterator = contactsList.iterator()
        for (i in iterator) {
            if (i.uid == name) {
                iterator.remove()
                break
            }
        }
        saveContactsList(context, contactsList)
    }

}